// pages/newIndex/newIndex.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIpt: true,
    req: false,
    active: 0,
    searchClear: false,
    more: false,
    showBtn: false,
    searchContent: '',
    pageEnd: false,
    param: {
      pageNumber: 1,
      pageSize: 10
    },
    hotList: [],
    searchList: [],
    historySearch: []
  },
  user(e) {
    var that = this;
    var id = e.currentTarget.dataset.createuid;
    var name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: '/pages/myCardNew/myCardNew?type=visitor&id=' + id + '&name=' + name,
    })
  },
  org(e) {
    console.log('org')
    var dataset = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/orgHome/orgHome?id=' + dataset.orgid
    })
  },
  onChange(e) {
    var that = this;
    that.toggle('searchList', [])
    that.toggle('active', e.detail.index)
    that.toSearch()
  },
  searchIpt(e) {
    var that = this
    if (!that.data.canIpt) {
      return
    }
    that.toggle('searchContent', e.detail.value)
    if (!e.detail.value) {
      that.toggle('searchClear', false)
      that.toggle('active', 0)
      that.getHeight()
    }
  },
  searchClear() {
    var that = this
    that.toggle('searchContent', '')
    that.toggle('searchClear', false)
    that.toggle('active', 0)
    that.toggle('searchList', [])
    that.getHeight()
  },
  clickSearch(e) {
    var that = this;
    var dataset = e.currentTarget.dataset;
    that.toggle('canIpt', false)
    that.toggle('searchContent', dataset.key)
    that.toSearch()
  },
  iptClick() {
    this.toSearch()
  },
  light(str) {
    console.log('关键字', this.data.searchContent)
    var index = str.indexOf(this.data.searchContent),
     i = this.data.searchContent.length,
     f = str.substring(0, index),
      s = str.substring(index, i + index),
      t = str.substring( i + index,str.length),
      arr = [f,s,t];
    return arr
     
  },
  toSearch(append) {
    var that = this;
    console.log(that.data.searchContent)
    if (that.data.searchContent.length) {
      that.toggle('searchClear', true)
    }
    that.toggle('req', false)
    if (that.data.active != 4){
      var type = that.data.active + 1
    }else{
      var type = 6
    }
    app.req({
      url: "orgmini/home/search",
      data: {
        keywords: that.data.searchContent,
        type: 0,
        pageNumber: that.data.param.pageNumber,
        pageSize: that.data.param.pageSize
      },
      success: function(res) {
        if (200 == res.code) {
          var searchList = res.data.rows
          console.log('查询列表', searchList)
          for (var item of searchList) {
            if (item.type==1){
              item.orgName = that.light(item.orgName)
            } else if (item.type == 2){
              item.name = that.light(item.realName).join("");
              item.realName = that.light(item.realName)
            } else if (item.type == 3) {
              item.topic = that.light(item.topic)
            } else if (item.type == 4 || item.type == 6) {
              item.topic = that.light(item.topic)
            }
            // console.log(item.orgName)
            if (item.createTime) {
              var timestamp = Date.parse(new Date());
              var date = new Date(timestamp);
              //获取年份  
              var Y = date.getFullYear();
              if (Y == item.createTime.substring(0, 4)) {
                item.createTime = item.createTime.substring(5, 7) + '月' + item.createTime.substring(8, 10) + '日 ' + item.createTime.substring(11, 16)
              } else {
                item.createTime = item.createTime.substring(0, 4) + '年' + item.createTime.substring(5, 7) + '月' + item.createTime.substring(8, 10) + '日 ' + item.createTime.substring(11, 16)
              }
            }
          }
          // if (that.data.active == 2) {
            for (var item of searchList) {
              if(item.type==3){
              if (item.actStartTime.substring(0, 10) == item.actEndTime.substring(0, 10)) {
                item.actTime = item.actStartTime.substring(5, 7) + '月' + item.actStartTime.substring(8, 10) + '日' + item.actStartTime.substring(11, 16) + '-' + item.actEndTime.substring(11, 16)
              } else {
                item.actTime = item.actStartTime.substring(5, 7) + '月' + item.actStartTime.substring(8, 10) + '日' + item.actStartTime.substring(11, 16) + '-' + item.actEndTime.substring(5, 7) + '月' + item.actEndTime.substring(8, 10) + '日' + item.actEndTime.substring(11, 16)
              }
              }
            }
          // }

          // if (!searchList || searchList.length < that.data.param.pageSize) {
          //   that.toggle("pageEnd", true);
          // }
          console.log('拼接', append)
          that.toggle("searchList", append ? that.data.searchList.concat(searchList) : searchList);
          wx.getStorage({
            key: 'historySearch',
            success(res) {
              var historySearch = res.data
              if (that.data.searchContent.length){
                if (historySearch.indexOf(that.data.searchContent) == -1) {
                  historySearch.unshift(that.data.searchContent)
                  wx.setStorage({
                    key: "historySearch",
                    data: historySearch,
                    success(res) {
                      that.toggle('historySearch', historySearch)
                    }
                  })
                } else {
                  historySearch.splice(historySearch.indexOf(that.data.searchContent), 1);
                  historySearch.unshift(that.data.searchContent)
                  wx.setStorage({
                    key: "historySearch",
                    data: historySearch,
                    success(res) {
                      that.toggle('historySearch', historySearch)
                    }
                  })
                }
              }

            }
          })
          that.toggle('req', true)
          that.toggle('canIpt', true)
        }

      }
    });
  },
  clearHistory() {
    var that = this
    that.toggle('historySearch', [])
    that.getHeight()
    wx.setStorage({
      key: "historySearch",
      data: []
    })
  },

  showMore() {
    var that = this
    that.toggle('more', !that.data.more)
  },

  activityDetail: function(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    wx.navigateToMiniProgram({
      appId: app.globalData.activityMiniAppId,
      envVersion: app.globalData.activityMiniEnvVersion,
      path: 'pages/register/register?id=' + id,
      success(res) {
        console.log(res);
      }
    })
  },

  // 热搜榜
  hotList: function() {
    var that = this;
    app.req({
      url: "orgmini/home/hotList",
      data: {},
      success: function(res) {
        if (200 == res.code) {
          var hotList = res.data
          that.toggle("hotList", hotList);
        }
      }
    });
  },


  friend: function(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    wx.navigateTo({
      url: '/pages/myCardNew/myCardNew?type=visitor&id=' + id + '&name=' + name,
    })
  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  toPage(e) {
    var dataset = e.currentTarget.dataset;
    var url = dataset.turn
    if (dataset.id) {
      url = url + '?id=' + dataset.id
    }
    if (dataset.orgid) {
      url = url + '&orgId=' + dataset.orgid
    }
    wx.navigateTo({
      url: url
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this
    wx.getStorage({
      key: 'historySearch',
      success(res) {
        that.toggle('historySearch', res.data)
        that.getHeight()
      },
      fail(res) {
        var arr = []
        wx.setStorage({
          key: "historySearch",
          data: arr
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this
    wx.getSetting({
      success(res) {
        // if (!res.authSetting['scope.userInfo'] || wx.getStorageSync('uid') == '') {
        if (wx.getStorageSync('uid') == '') {
          that.hotList();
        } else {
          app.getUserInfo(function(userInfo) {
            that.hotList();
          });
        }
      },
    })

  },


  getHeight() {
    var query = wx.createSelectorQuery();
    //选择id
    var that = this;
    query.select('#h-box').boundingClientRect(function(rect) {
      if (rect) {
        if (rect.height > 78) {
          that.setData({
            showBtn: true
          })
        } else {
          that.setData({
            showBtn: false
          })
        }
      }
    }).exec();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var that = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userInfo']) {
          if (!that.data.searchClear) {
            that.hotList();
            wx.getStorage({
              key: 'historySearch',
              success(res) {
                that.toggle('historySearch', res.data)
                that.getHeight()
              }
            })
          } else {
            that.toggle("param.pageNumber", 1);
            that.toggle("pageEnd", false);
            that.toggle("searchList", []);
            that.toSearch()
          }
        } else {
          app.getUserInfo(function(userInfo) {
            if (!that.data.searchClear) {
              that.hotList();
              wx.getStorage({
                key: 'historySearch',
                success(res) {
                  that.toggle('historySearch', res.data)
                  that.getHeight()
                }
              })
            } else {
              that.toggle("param.pageNumber", 1);
              that.toggle("pageEnd", false);
              that.toggle("searchList", []);
              that.toSearch()
            }

          });
        }
      },
    })

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;
    if (!that.data.pageEnd && that.data.searchClear) {
      that.toggle("param.pageNumber", that.data.param.pageNumber + 1);
      that.toSearch(true);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})